import React, { useEffect, useState } from 'react';
import { useMatches, useNavigate, useLocation } from 'react-router-dom';
import { Menu } from 'antd';
import { useMenu } from '@/store/app';
import './index.scss';

const LayoutMenu: React.FC = () => {
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const menus = useMenu(state => state.menus);
  let navigate = useNavigate();
  let location = useLocation();
  let matches = useMatches();
  let handle = matches[matches.length - 1].handle as any;
  let selectedKey = handle.menuKey || matches[matches.length - 1].pathname;
  let defaultKeys = [selectedKey];

  useEffect(() => {
    let openKey = handle?.openKey;
    let firstOpenKeys = openKey ? [openKey] : [];
    setOpenKeys(openKeys => [...openKeys, ...firstOpenKeys]);
  }, [location]);
  return (
    <div>
      <Menu
        style={{ width: '200px' }}
        openKeys={openKeys}
        selectedKeys={defaultKeys}
        mode="inline"
        onClick={item => {
          navigate(item.key);
        }}
        onOpenChange={setOpenKeys}
        items={menus}
        className="menu-div"></Menu>
    </div>
  );
};

export default LayoutMenu;
